<template>
    <div id="add-edit-InspectionRoute">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="100px" :rules="rules">
                <el-row>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="巡检线路" prop="v_Name">
                            <el-input v-model="ruleForm.v_Name" placeholder="请输入巡检线路" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="巡检部门" prop="l_OrgId">
                            <el-cascader 
                                v-model="ruleForm.l_OrgId"
                                :options="orgOption" 
                                :props="orgProps" 
                                filterable
                                @change="orgChange"
                                clearable 
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="层级" prop="v_Levele">
                            <el-select 
                                filterable
                                class="m-2" 
                                placeholder="请选择层级" 
                                v-model="ruleForm.v_Levele" 
                                multiple
                                collapse-tags
                            >
                                <el-option
                                    v-for="item in typeOption"
                                    :key="item.id"
                                    :label="item.value"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , watch } from 'vue';
import { FormInstance, FormRules, ElButton, ElCol, ElDialog, ElForm, ElFormItem, ElInput, ElRow } from 'element-plus';
import { sysOrgTree , sysDictDataList } from '/@/api/centerControl/pubilc';
import { SMSIPPathAdd , SMSIPPathUpdate } from '/@/api/centerControl/sms';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    v_Name: String, // 巡检线路名称
    l_OrgId: any, // 部门Id
    v_Levele: String, // 层级
}
export default defineComponent( {
    name: 'add-edit-InspectionRoute',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        const orgOption = ref();
        const typeOption = ref();

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 巡检线路名称
            v_Name: [
				{ required: true, message: '请输入巡检线路名称', trigger: 'blur' },
			],
            // 部门
            l_OrgId: [
				{ required: true, message: '请选择部门', trigger: 'change' },
			],
            // 部门
            v_Levele: [
				{ required: true, message: '请选择层级', trigger: 'change' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** orgChange 巡检部门改变事件 */
        const orgChange = (val: any) => {
            let len = val.length - 1;
            if(val && val.length !== 0){
                state.ruleForm.l_OrgId = val[len];
            }
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    let param: any = toRaw(state.ruleForm);
                    let getStr = '';
                    param.v_Levele.map((item: any) => {
                        getStr += (item + ',');
                    });
                    param.v_Levele = getStr.slice(0,-1);
                    state.repeatDis = true;
                    try{
                        let res: any;
                        if(props.repairInfo !== ''){
                            res = await SMSIPPathUpdate(param);
                        }else{
                            res = await SMSIPPathAdd(param);
                        }
                        if(res.success){
                            state.repeatDis = false;
                            ctx.emit('updateData');
                            ctx.emit('controlUseClick');
                        }else{
                            state.repeatDis = false;
                            ctx.emit('controlUseClick');
                        }
                    }catch(error){ state.repeatDis = false; }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** getTree 获取组织架构树 */
        const getTree = async() => {
            let param = {}
            let res: any = await sysOrgTree(param);
            if(res.success) orgOption.value = res.data;

            let ras: any = await sysDictDataList({ TypeCode: 'InspectionLevel' });
            if(ras.success) typeOption.value = ras.data;
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                getTree();
                state.repeatDis = false;
                if(props.repairInfo !== ''){
                    titleCon.value = '编辑';
                    let getData = JSON.parse(props.repairInfo);
                    getData.v_Levele = JSON.parse(props.repairInfo).v_Levele.split(',');
                    state.ruleForm = getData;
                }else{
                    titleCon.value = '新增';
                    state.ruleForm = {
                        v_Name: '', // 巡检线路名称
                        l_OrgId: 0, // 部门Id
                        v_Levele: '', // 层级
                    }
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            orgProps: { checkStrictly: true , label: 'title', value: 'id', children: 'children' },
            orgOption,
            orgChange,
            typeOption,
        }
    },
} )
</script>
<style scoped lang="scss">
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
</style>